﻿

using System.Diagnostics;

namespace IotClientService;
public class WindowProcessService
{
    /// <summary>
    /// 获取cpu和内存占用信息
    /// </summary>
    /// <returns></returns>
    public static (int, int) GetCupAndRam()
    {
        var process = Process.GetCurrentProcess();
        var workingSet64 = (int)(process.WorkingSet64 / 1024 / 1024);

        var cpu = GetCpuUsageForProcess();

        return ((int)cpu, workingSet64);
    }


    private static DateTime? _previousCpuStartTime = null;
    private static TimeSpan? _previousTotalProcessorTime = null;

    /// <summary>
    /// 获取cpu运行数据
    /// </summary>
    /// <returns></returns>
    private static double GetCpuUsageForProcess()
    {
        var currentCpuStartTime = DateTime.UtcNow;
        var currentCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;

        // If no start time set then set to now
        if (!_previousCpuStartTime.HasValue)
        {
            _previousCpuStartTime = currentCpuStartTime;
            _previousTotalProcessorTime = currentCpuUsage;
        }

        var cpuUsedMs = (currentCpuUsage - _previousTotalProcessorTime.Value).TotalMilliseconds;
        var totalMsPassed = (currentCpuStartTime - _previousCpuStartTime.Value).TotalMilliseconds;
        var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);

        // Set previous times.
        _previousCpuStartTime = currentCpuStartTime;
        _previousTotalProcessorTime = currentCpuUsage;

        return cpuUsageTotal * 100.0;
    }

    /// <summary>
    /// 获取本地Ip地址
    /// </summary>
    /// <returns></returns>
    public static string GetLocalIp()
    {
        var addressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
        var ips = addressList.Where(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                .Select(address => address.ToString()).ToArray();
        if (ips.Length == 1)
        {
            return ips.First();
        }
        return ips.Where(address => !address.EndsWith(".1")).FirstOrDefault() ?? ips.FirstOrDefault();
    }
}
